package com.weakteam.orderonline.adminconsole.gwt.client.widget;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.logical.shared.*;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
import com.weakteam.orderonline.adminconsole.gwt.client.domain.Place;

/**
 * Created by Max on 30.03.2014.
 */
public class PlacesContainer extends FlowPanel implements
    HasSelectionHandlers<PlacesBox>, HasOpenHandlers<Place> {


    public PlacesContainer(AbsolutePanel dragSpace) {
        dragSpace.add(this);
        this.addStyleName("content-container");
    }

    @Override
    public HandlerRegistration addSelectionHandler(SelectionHandler<PlacesBox> handler) {
        return super.addHandler(handler, SelectionEvent.getType());
    }
    @Override
    public HandlerRegistration addOpenHandler(OpenHandler<Place> handler) {
        return super.addHandler(handler, OpenEvent.getType());
    }

    private void addBox(final PlacesBox box) {
        this.add(box);
        box.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                PlacesContainer.this.setBoxSelected(box);
            }
        });
        box.addDoubleClickHandler(new DoubleClickHandler() {
            @Override
            public void onDoubleClick(DoubleClickEvent event) {
                OpenEvent.fire(PlacesContainer.this,box.getPlace());
            }
        });

    }

    protected void setBoxSelected(PlacesBox newSelectedBox) {
        for (Widget box : this.getChildren()) {
            if (box instanceof PlacesBox) {
                PlacesBox tBox = (PlacesBox)box;
                if (tBox.isSelected()) {
                    tBox.setSelected(false);
                }
            }
        }
        newSelectedBox.setSelected(true);
        SelectionEvent.fire(this,newSelectedBox);
    }

    public void setData(JSONArray data) {
        this.clear();
        int n = data.size();
        if (n > 0) {
            for(int i = 0; i < n; i++) {
                JSONObject obj = data.get(i).isObject();
                final Place place = new Place(obj);
                addBox(new PlacesBox(place));
            }
        }
    }

}
